package com.oazon.voicelib.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.UnderstanderResult;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.speech.UtilityConfig;
import com.moco.launcher.R;
import com.oazon.voicelib.model.MusicSemantic;
import com.oazon.voicelib.model.SemanticObj;
import com.oazon.voicelib.model.MusicSemantic.Slots;
import com.oazon.common.Logger;
import com.oazon.common.util.JsonParser;
import com.oazon.common.util.SDcradUtil;
import com.oazon.common.util.Utils;

public class SpeechServer extends Service {

	private static final String TAG = "SpeechServer";
	private static int MAX_TIMES = 3;
	private boolean isWakeWarm = false;
	/**
	 * 计数器，count次没说话则进入语音唤醒状态
	 */
	private int count = 0;

	MyBind MyBind = new MyBind();
	SpeechUtil speechUtil;
	private Talker talker;

	public void registTalker(Talker talker) {
		this.talker = talker;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		speechUtil = new SpeechUtil(this);
	}

	/**
	 * 开始唤醒功能״̬
	 */
	public void startWake() {
		speechUtil.startWake(wakeuperListener);
		count = 0;
	}

	public void stopWake() {
		speechUtil.stopWake();
	}

	/**
	 * 开始语义识别功能
	 */
	public void startUnderstand() {
		if (!speechUtil.isUnderstand()) {
			speechUtil.stopWake();
			if (count < MAX_TIMES) {
				Logger.d(TAG, "startUnderstand");
				speechUtil.startUnderstandSpeech(speechUnderstanderListener);
			} else {
				Logger.d("OAZON", "AUTO+++startWake");
				startWake(); 
			}
		}
	}

	/**
	 * 
	 * @param key
	 *            SpeechConstant.IVW_SST:唤醒or训练 SpeechConstant.KEEP_ALIVE:是否保持唤醒
	 *            SpeechConstant.IVW_WORD_PATH:训练、合并后生成的资源路径
	 *            SpeechConstant.IVW_THRESHOLD:唤醒门限值
	 * @param value
	 * 
	 */
	public void setWakeParameter(String key, String value) {
		speechUtil.setWakeParameter(key, value);
	}

	/**
	 * 
	 * @param key
	 *            SpeechConstant.NET_TIMEOUT:网络连接超时时间
	 *            SpeechConstant.KEY_SPEECH_TIMEOUT:语音输入超时时间
	 *            SpeechConstant.LANGUAGE:语言 SpeechConstant.ACCENT:语言区域
	 *            SpeechConstant.DOMAIN:应用领域 SpeechConstant.AUDIO_SOURCE:音频源
	 *            SpeechConstant.VAD_BOS:前端点超时 SpeechConstant.VAD_EOS:后端点超时
	 *            SpeechConstant.SAMPLE_RATE:识别采样率
	 *            SpeechConstant.ASR_PTT:设置是否有标点符号
	 *            SpeechConstant.RESULT_TYPE:识别结果类型
	 *            SpeechConstant.SEARCH_AREA:地图搜索设置区域
	 *            SpeechConstant.ASR_AUDIO_PATH识别录音保存路径
	 * @param value
	 */
	public void setUnderstanderParameter(String key, String value) {

		speechUtil.setUnderstanderParameter(key, value);
	}

	/**
	 * 
	 * @param key
	 *            SpeechConstant.VOICE_NAME:发音人设置 SpeechConstant.SPEED:语速
	 *            SpeechConstant.VOLUME:合成的音量 SpeechConstant.PITCH:语调
	 *            SpeechConstant.BACKGROUND_SOUND:背景音乐
	 *            SpeechConstant.TTS_BUFFER_TIME:合成音频缓冲时间
	 *            SpeechConstant.STREAM_TYPE:播放类型
	 *            SpeechConstant.KEY_REQUEST_FOCUS:设置是否会话过程中暂停后台音乐播放
	 *            SpeechConstant.TTS_AUDIO_PATH:合成录音保存路径
	 *            SpeechConstant.SAMPLE_RATE:合成采样率
	 * @param value
	 */
	public void setTtsParameter(String key, String value) {

		speechUtil.setTtsParameter(key, value);
	}

	/**
	 * 关闭语音识别
	 */
	public void stopUnderstand() {
		speechUtil.stopSpeechUnderstander();
		startWake();
	}

	@Override
	public IBinder onBind(Intent intent) {
		startWake();
		return MyBind;
	}

	public class MyBind extends Binder {
		public SpeechServer getService() {
			return SpeechServer.this;
		}
	}

	private OnWakeuperListener onWakeuperListener;

	public void registWakeuperListener(OnWakeuperListener listener) {
		onWakeuperListener = listener;
	}

	private WakeuperListener wakeuperListener = new WakeuperListener() {

		@Override
		public void onResult(WakeuperResult arg0) {
			Log.i("michael", "wakeuperListener+onResult");

			Logger.i(TAG, "wakeResultString ====" + arg0.getResultString()
					+ "||describeContents" + arg0.describeContents());
			
	/*		try {
				SDcradUtil.saveToSDCard(TAG+".txt", "wakeResultString ====" + arg0.getResultString()
						+ "||describeContents" + arg0.describeContents()+"\r\n", getApplicationContext());
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			/*
			 * MediaPlayer mp = MediaPlayer.create(SpeechServer.this,
			 * R.raw.standby); mp.setOnCompletionListener(new
			 * OnCompletionListener() {
			 * 
			 * @Override public void onCompletion(MediaPlayer mp) { try {
			 * Log.i("michael", "wakeuperListener+onResult");
			 * onWakeuperListener.onWakeuper(); isWakeWarm = true;
			 * Log.i("michael", "isWakeWarm===="+isWakeWarm); if (isWakeWarm) {
			 * count = 0; talker.wakeUnderstand();
			 * 
			 * } else { count = MAX_TIMES; startUnderstand();
			 * 
			 * } talker.endTts(isWakeWarm); isWakeWarm = false; } finally {
			 * mp.release(); } } }); mp.start();
			 */

			Log.i("michael", "wakeuperListener+onResult");
			//wifi未连接，不进行语音识别；
			if(!Utils.isWifiConnected(SpeechServer.this)){
				Toast.makeText(SpeechServer.this, "WiFi未连接", Toast.LENGTH_SHORT).show();
				return;
			}
			
			onWakeuperListener.onWakeuper();
			isWakeWarm = true;
			Log.i("michael", "isWakeWarm====" + isWakeWarm);
			if (isWakeWarm) {
				count = 0;
				talker.wakeUnderstand();

			} else {
				count = MAX_TIMES;
				startUnderstand();

			}
			talker.endTts(isWakeWarm);
			isWakeWarm = false;
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			Log.i("OAZON", "wakeuperListener+onEvent");
		}

		@Override
		public void onError(SpeechError arg0) {
			Log.i("OAZON", "wakeuperListener+onError");
			startWake();
		}

		@Override
		public void onBeginOfSpeech() {
			Log.i("OAZON", "wakeuperListener+onBeginOfSpeech");
		}
	};

	private SpeechUnderstanderListener speechUnderstanderListener = new SpeechUnderstanderListener() {

		@Override
		public void onVolumeChanged(int arg0) {
			// Log.i("OAZOM", "speechUnderstanderListener+onVolumeChanged");
			if (talker == null) {
				Toast.makeText(getApplicationContext(), "请到语音界面",
						Toast.LENGTH_SHORT).show();
				return;
			}
			talker.talkVolume(arg0);

		}

		@Override
		public void onResult(UnderstanderResult arg0) {

			Log.i("OAZON", arg0.getResultString());
			Log.i("time",
					"speechUnderstanderListener===" + arg0.getResultString());
			Log.i("OAZON", "onResult_count====" + count);
			SemanticObj obj = JSON.parseObject(arg0.getResultString(),
					SemanticObj.class);

			if (obj.getRc() != 0 && obj.getRc() != 4) {
				talker.onUnderstandError("错了错了");
		/*		speechUtil.startSpeechSynthesizer("对不起,出错了",
						synthesizerListener);*/
				count = MAX_TIMES;
				startUnderstand();
			} else if (obj.getRc() == 4) {
				//TODO 语音播放，对不起，我不懂
/*				MediaPlayer mp = MediaPlayer.create(SpeechServer.this,
						R.raw.dontunderstand);
				mp.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.release();
					}
				});
				mp.start();*/
				talker.talkUnderstandRs(obj.getText());
				talker.onUnderstandError("我不理解");
				count = MAX_TIMES;
				startUnderstand();
			} else if (obj.getSemantic() != null) {
				SemanticObj result = JsonParser.ObjToObj(obj);

				if ("music".equals(result.getService())
						&& "PLAY".equals(result.getOperation())) {
					Slots slots = ((MusicSemantic) result.getSemantic())
							.getSlots();

					if (slots != null) {

						String song = slots.getSong();
						String artist = slots.getArtist();
						String album = slots.getAlbum();

						if (result.getService() != null && song != null
								&& !"".equals(song)) {
							// speechUtil.startSpeechSynthesizer("正在寻找" + song,
							// synthesizerListener);
							count = MAX_TIMES;
						} else if (result.getService() != null
								&& artist != null && !"".equals(artist)) {
							// speechUtil.startSpeechSynthesizer("正在寻找" + artist
							// + "的歌曲", synthesizerListener);
							count = MAX_TIMES;
						} else if (result.getService() != null && album != null
								&& !"".equals(album)) {
							// speechUtil.startSpeechSynthesizer("正在寻找" + album
							// + "专辑的歌曲", synthesizerListener);
							count = MAX_TIMES;
						}

						if (isWakeWarm) {
							count = 0;
							talker.wakeUnderstand();
						} else {
							count = MAX_TIMES;
							startUnderstand();
						}
						isWakeWarm = false;
					}
				}
				talker.talkUnderstandRs(result);
			}
			Log.i("OAZON", "speechUnderstanderListener+onResult");
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			Log.i("OAZON", "speechUnderstanderListener+onEvent");
		}

		/**
		 * 当不讲话时进入
		 */
		@Override
		public void onError(SpeechError arg0) {
			// speechUtil.startSpeechSynthesizer("",
			// synthesizerListener);
			count = MAX_TIMES;
			startUnderstand();
			Log.i("OAZON", "speechUnderstanderListener+onError");
			Log.i("OAZON", "speechUnderstanderListener+" + arg0.getErrorCode());
			talker.onUnderstandError(arg0.getErrorDescription());
		}

		@Override
		public void onEndOfSpeech() {
			Log.i("OAZON", "speechUnderstanderListener+onEndOfSpeech");
			talker.onEndOfUnderstander();
		}

		@Override
		public void onBeginOfSpeech() {
			Log.i("OAZON", "speechUnderstanderListener+onBeginOfSpeech");
		}
	};

	@Deprecated
	private SynthesizerListener synthesizerListener = new SynthesizerListener() {

		@Override
		public void onSpeakResumed() {
			Log.i("OAZON", "synthesizerListener+onSpeakResumed");
		}

		@Override
		public void onSpeakProgress(int arg0, int arg1, int arg2) {
			// Log.i("OAZOM", "synthesizerListener+onSpeakProgress");
		}

		@Override
		public void onSpeakPaused() {
			Log.i("OAZON", "synthesizerListener+onSpeakPaused");
		}

		@Override
		public void onSpeakBegin() {
			Log.i("OAZON", "synthesizerListener+onSpeakBegin");
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			Log.i("OAZON", "synthesizerListener+onEvent");
		}

		@Override
		public void onCompleted(SpeechError arg0) {
			Log.i("OAZON", "synthesizerListener+onCompleted");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (isWakeWarm) {
				count = 0;
				talker.wakeUnderstand();
			} else {
				count = MAX_TIMES;
				startUnderstand();
			}
			talker.endTts(isWakeWarm);
			isWakeWarm = false;
		}

		@Override
		public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {
			Log.i("OAZON", "synthesizerListener+onBufferProgress");
		}
	};

	public void destroy() {
		speechUtil.destroyTts();
		speechUtil.destroyUnderstander();
		speechUtil.destroyWake();
	}

	public void startSpeechSynthesizer(String string) {
		speechUtil.startSpeechSynthesizer(string, synthesizerListener);

	}

	public void stopSeechSynthesizer() {
		startWake();
		speechUtil.stopSeechSynthesizer();
	}
}
